/**
 * 
 */
package operation;

import java.util.ArrayList;
import java.util.List;

import common.Logger;

/**
 * This is the deployment scripts for setting up
 * new environments.
 * 
 * @author chuxiaoyuan
 *
 */
public abstract class Deploy {

	/**
	 * Indicate if turn deployment option.
	 */
	static final boolean TURN_ON = true;
	
	static {
		/**
		 * Deployment steps registration here.
		 */
		
		// Root User: SysAdmin
		REGISTER(new InitializeUsers());
	}
	
	/**
	 * Get description.
	 * 
	 * @return the description
	 */
	public abstract String getDescription();

	/**
	 * Run the deployment script.
	 * 
	 * @return true if run successfully, otherwise false.
	 */
	public abstract boolean run() throws Exception;

	/**
	 * The registered operations.
	 */
	private static List<Deploy> OPERATIONS;
	
	/**
	 * Register an instance. 
	 * 
	 * @param instance The Deploy instance.
	 */
	private static <T extends Deploy> void REGISTER(T instance) {
		if (OPERATIONS == null) {
			OPERATIONS = new ArrayList<Deploy>();
		}
		OPERATIONS.add(instance);
	}
	
	/**
	 * Logger.
	 */
	private static  Logger logger = new Logger(Deploy.class);
	
	/**
	 * Execute all deployment scripts.
	 */
	public static void execute() throws Exception {
		
		/**
		 * Run all scripts
		 */
		for (Deploy d : OPERATIONS) {
			try {
				logger.log("[" + d.getClass() + "] " + 
						d.getDescription() + " deploy...");
				if (!d.run()) {
					String msg = 
							"Deployment failed for: " + d.getDescription();
					logger.error(msg);
					throw new Exception(msg);
				}
				logger.log("DONE.");
				
			} catch (Exception e) {
				
				String msg = 
						"Deployment exception occurred for: " + 
								d.getDescription();
				logger.error(msg, e);
				throw new Exception(msg);
			}
		}
	}

}
